package org.octopus.data.desensitized.core.spring.registry;

import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.octopus.data.desensitized.core.registry.DesensitizedStrategyRegistry;
import org.octopus.data.desensitized.core.registry.impl.DefaultDesensitizedStrategyRegistry;
import org.octopus.data.desensitized.core.strategy.DesensitizedStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author lemon
 * @date 2021/8/28 11:15
 */
@Slf4j
public class SpringDesensitizedStrategyRegistry extends DefaultDesensitizedStrategyRegistry implements
        DesensitizedStrategyRegistry, InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, DesensitizedStrategy> desensitizedStrategies =
                this.applicationContext.getBeansOfType(DesensitizedStrategy.class);

        if (MapUtils.isNotEmpty(desensitizedStrategies)) {
            desensitizedStrategies.forEach((beanName, desensitizedStrategy) -> {
                SpringDesensitizedStrategyRegistry.this.register(desensitizedStrategy);
                log.info("注册脱敏策略[{}]，类型是：{}", beanName, desensitizedStrategy);
            });
        }
    }
}
